package dk.mirasola.systemtraining.bridgewidgets.shared.model.distributionfiltertree;

import dk.mirasola.systemtraining.bridgewidgets.shared.model.Distribution;
import dk.mirasola.systemtraining.bridgewidgets.shared.model.Seat;

import java.util.HashSet;
import java.util.Set;


public final class HcpSeatDistributionFilter extends DistributionFilterGroupItem {
    private Set<Seat> seats = new HashSet<Seat>();
    private HcpInterval hcpInterval = new HcpInterval();

    /**
     * Returns set of SEATS for which sum of hcp must in the hcp interval
     *
     * @return set of SEATS for which sum of hcp must in the hcp interval
     */
    public Set<Seat> getSeats() {
        return seats;
    }

    public void setSeats(Set<Seat> seats) {
        if (seats == null) {
            throw new NullPointerException();
        }
        this.seats = seats;
    }

    public HcpInterval getHcpInterval() {
        return hcpInterval;
    }

    public void setHcpInterval(HcpInterval hcpInterval) {
        if (hcpInterval == null) {
            throw new NullPointerException();
        }
        this.hcpInterval = hcpInterval;
    }


    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("hcp(");
        for (Seat seat : seats) {
            builder.append(seat);
            builder.append(",");
        }
        builder.deleteCharAt(builder.length() - 1);
        if (hcpInterval.getMinHcp() != hcpInterval.getMaxHcp()) {
            builder.append(") between ").append(hcpInterval.getMinHcp()).append(" and ").append(hcpInterval.getMaxHcp());
        } else {
            builder.append(")=").append(hcpInterval.getMinHcp());
        }
        return builder.toString();
    }


    protected boolean matchesInternal(Distribution distribution) {
        if (seats.isEmpty())
            return true;

        // calculate hcp
        int hcp = 0;

        for (Seat seat : seats) {
            // hcp for hand
            hcp += distribution.getHand(seat).getHcp();
        }

        // is hcp of hands between min and max?
        return hcpInterval.contains(hcp);
    }

    @Override
    public boolean isCopy(GroupItem groupItem) {
        if (!super.isCopy(groupItem)) return false;
        if (!(groupItem instanceof HcpSeatDistributionFilter)) return false;

        HcpSeatDistributionFilter that = (HcpSeatDistributionFilter) groupItem;
        return hcpInterval.equals(that.hcpInterval) && seats.equals(that.seats);
    }

    @Override
    public HcpSeatDistributionFilter copy() {
        HcpSeatDistributionFilter copy = new HcpSeatDistributionFilter();
        copy.setInverted(this.getInverted());
        copy.seats.addAll(this.seats);
        copy.hcpInterval = this.hcpInterval.copy();
        return copy;
    }
}
